package util;

import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.ws.util.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
 * @Author: WangYongGan
 * @Date: 2021/11/1 19:27
 * @Description:
 */
public class HttpUtil {
//    public static String doGet(String url) throws MalformedURLException {
//        String res = null;
//        HttpClient client = new HttpClient();
//        client.startSession(new URL(url));
//        GetMethod getMethod = new GetMethod(url);
//        int code = 0;
//        try {
//            code = client.executeMethod(getMethod);
//            System.out.println(code);
//            if (code == 200) {
//                res = getMethod.getResponseBodyAsString();
//                System.out.println(res);
//            }
//        } catch (IOException | HttpException e) {
//            e.printStackTrace();
//        }
//        return res;
//    }
//    public static String doPost(String url, Map<String, Object> paramMap) {
//        String res = null;
//        HttpClient client = new HttpClient();
//        PostMethod postMethod = new PostMethod(url);
//        postMethod.addRequestHeader("Content-type","application/json;charset=utf-8");
//        Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<String, Object> next = iterator.next();
//            postMethod.addParameter(next.getKey(), next.getValue().toString());
//        }
//        try {
//            int code = client.executeMethod(postMethod);
//            if (code == 200) {
//                res = postMethod.getResponseBodyAsString();
//            }
//        } catch (IOException | HttpException e) {
//            e.printStackTrace();
//        }
//        return res;
//    }
    public static void test() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet("http://httpbin.org/get");
            // The underlying HTTP connection is still held by the response object
            // to allow the response content to be streamed directly from the network socket.
            // In order to ensure correct deallocation of system resources
            // the user MUST call CloseableHttpResponse#close() from a finally clause.
            // Please note that if response content is not fully consumed the underlying
            // connection cannot be safely re-used and will be shut down and discarded
            // by the connection manager.
            try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
                System.out.println(response1.getStatusLine() + " " + response1.getAllHeaders());
                response1.getStatusLine().getStatusCode();
                HttpEntity entity1 = response1.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                EntityUtils.consume(entity1);
            }

            HttpPost httpPost = new HttpPost("http://httpbin.org/post");
            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("username", "vip"));
            nvps.add(new BasicNameValuePair("password", "secret"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));

            try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
//                System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
                HttpEntity entity2 = response2.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                EntityUtils.consume(entity2);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String getUrl="http://localhost:8001/student/getName";
        String postUrl="http://localhost:8001/postArr";
        List<String> params=new ArrayList<>();
        params.add("wang");
        params.add("zhang");
//        doGet(url);te
        test();
        doHttpRequest(postUrl,params.toString());
        doHttpRequest(postUrl, JSONObject.toJSONString(params));
    }

    public static String doHttpRequest(String url, String param) {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
            connection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.addRequestProperty("User-Agent", "mytest");
            connection.setConnectTimeout(60000);
            connection.setReadTimeout(60000);
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            if(param !=null &&!param.equals(""))
                connection.getOutputStream().write(param.getBytes("utf8"));
            int status = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuffer message = new StringBuffer();
            while (reader.ready()) {
                message.append(reader.readLine());
            }
            System.out.println(message);
            reader.close();
            connection.connect();
            if (status == 200) {
                return  message.toString();
            }

        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}
